<template>
  <div>
    <div class="container">
      <div class="search-box">
        <el-input
          v-model="query.name"
          placeholder="议题名称"
          class="search-input mr10"
          clearable
        ></el-input>
        <el-button type="primary" :icon="Search" @click="handleSearch()"
          >搜索</el-button
        >
        <!-- <el-button
          type="warning"
          :icon="CirclePlusFilled"
          @click="visible = true"
          >新增</el-button
        > -->
      </div>
      <el-table
        :data="tableData"
        border
        class="table"
        ref="multipleTable"
        header-cell-class-name="table-header"
      >
        <!-- <el-table-column
          v-for="(value, index) in columns"
          :key="index"
          :prop="value.prop"
          :label="value.label"
          align="center"
        ></el-table-column> -->

        <el-table-column
          prop="name"
          label="议题名称"
          align="center"
        ></el-table-column>
        <el-table-column prop="publicity" label="公开程度" align="center">
          <template #default="scope">
            <el-tag
              :type="scope.row.publicity === 'True' ? 'success' : 'danger'"
            >
              {{ scope.row.publicity === "True" ? "公开" : "秘密" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="reporter"
          label="汇报人"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="preset_time"
          label="上传时间"
          align="center"
        ></el-table-column>

        <el-table-column prop="state" label="审核情况" align="center">
          <template #default="scope">
            <el-tag :type="stateTypeMapping[scope.row.state]">
              {{ scope.row.state }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column
          v-show="!is_admin"
          prop="proposal"
          label="审核意见"
          align="center"
        ></el-table-column>

        <el-table-column label="操作" width="280" align="center">
          <template #default="scope">
            <el-button
              v-if="(myname===scope.row.reporter) || ((scope.row.state === '驳回') === is_admin )"
              type="warning"
              size="small"
              :icon="View"
              @click="handleView(scope.row)"
            >
              查看
            </el-button>
            <el-button
              v-else
              type="primary"
              size="small"
              :icon="Edit"
              @click="handleEdit(scope.$index, scope.row)"
              v-permiss="15"
            >
              <div v-if="is_admin && scope.row.reporter!==myname">审核</div>
              <div v-else-if="!is_admin ">编辑</div>
            </el-button>

            <el-button
              type="danger"
              size="small"
              :icon="Delete"
              @click="handleDelete(scope.$index)"
              v-permiss="16"
            >
              结束
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          layout="total, prev, pager, next"
          :current-page="query.pageIndex"
          :page-size="query.pageSize"
          :total="pageTotal"
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </div>
    <el-dialog
      :title="is_admin  ? '审核议题' : '修改议题'"
      v-model="visible"
      width="500px"
      destroy-on-close
      :close-on-click-modal="false"
      @close="closeDialog"
    >
      <TableEdit :data="rowData" :edit="idEdit" :update="updateData" />
    </el-dialog>
    <el-dialog
      title="查看议题详情"
      v-model="visible1"
      width="700px"
      destroy-on-close
    >
      <TableDetail :data="rowData" />
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="basetable">
import { ref, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Delete,
  Edit,
  Search,
  View,
} from "@element-plus/icons-vue";
import TableEdit from "../components/table-edit.vue";
import TableDetail from "../components/table-detail.vue";
import axios from "../utils/request";

interface TableItem {
  [key: string]: string | number;
}

const stateTypeMapping: Record<string, string> = {
  通过: "success",
  送审: "",
  上会: "info", // 默认值
  驳回: "danger", // 默认值
};

var ro_issue: TableItem[];
let myname=localStorage.getItem("ms_username");
let is_admin = localStorage.getItem("role") === "admin";

// const columns = [
//   { label: "议题名称", prop: "name" },
//   { label: "公开程度", prop: "publicity" },
//   { label: "汇报人", prop: "reporter" },
//   { label: "上传时间", prop: "preset_time" },
//   { label: "审核情况", prop: "state" },
// ];

const query = reactive({
  address: "",
  name: "",
  pageIndex: 1,
  pageSize: 10,
});
const tableData = ref<TableItem[]>([]);
const pageTotal = ref(0);
// 获取表格数据
const getData = async () => {
  const res = await axios.get("/ro_issue/viewsets/");
  ro_issue = res.data.results as TableItem[];
  ro_issue = ro_issue.filter((i) => i.state !== "完结");

  if (is_admin) {
    // ro_issue = ro_issue.filter(
    //   (i) => i.reporter !== localStorage.getItem("ms_username")
    // );
  } else {
    ro_issue = ro_issue.filter(
      (i) => i.reporter === localStorage.getItem("ms_username")
    );
  }
  console.log(ro_issue);

  // ro_issue = ro_issue.map(({ id, ...rest }) => rest);
  // ro_issue = ro_issue.map((obj) => {
  //   return {
  //     ...obj,
  //     publicity: obj.publicity ? "公开" : "秘密",
  //   };
  // });
  tableData.value = ro_issue;
  pageTotal.value = ro_issue.length || 10;
};
getData();

// 查询操作
const handleSearch = () => {
  tableData.value = ro_issue.filter((i) => {
    i.name = i.name.toString();
    return i.name.includes(query.name);
  });
};
// 分页导航
const handlePageChange = (val: number) => {
  query.pageIndex = val;
  getData();
};

// 删除操作
const handleDelete = (index: number) => {
  // 二次确认删除
  ElMessageBox.confirm("议题已经结题了吗？", "提示", {
    type: "warning",
  })
    .then(() => {
      ElMessage.success("删除成功");
      tableData.value.splice(index, 1);
    })
    .catch(() => {});
};

const visible = ref(false);
let idx: number = -1;
const idEdit = ref(false);
const rowData = ref({});
const handleEdit = (index: number, row: TableItem) => {
  idx = index;
  rowData.value = row;
  idEdit.value = true;
  visible.value = true;

  // axios.put(`/issue/viewsets/${row.id}`,{
  //   state:''
  // })
};
const updateData = (row: TableItem) => {
  idEdit.value ? (tableData.value[idx] = row) : tableData.value.unshift(row);

  console.log(row);

  // 管理员审核----------------------
  if (is_admin) {
    axios
      .put(`/issue/viewsets/${row.id}/`, {
        state: row.state,
        proposal: row.proposal,
      })
      .then((res) => res.data)
      .then((data) => console.log("Put---------------", data));
  }
  // 普通用户修改后提交--------------
  else {
    row.state = "送审";
    axios
      .put(`/issue/viewsets/${row.id}/`, row)
      .then((res) => res.data)
      .then((data) => console.log("Put---------------", data));
  }

  closeDialog();
};

const closeDialog = () => {
  visible.value = false;
  idEdit.value = false;
};

const visible1 = ref(false);
const handleView = (row: TableItem) => {
  rowData.value = row;
  visible1.value = true;
};
</script>

<style scoped>
.search-box {
  margin-bottom: 20px;
}

.search-input {
  width: 200px;
}

.mr10 {
  margin-right: 10px;
}

.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
</style>
